<?php

namespace front\modules\web\controllers;

use messages\models\LogisticsMsg;
use messages\models\SystemMsg;
use messages\services\LogisticService;
use order\models\search\OrdersSearch;
use Yii;
use yii\data\ActiveDataProvider;
use front\controllers\WebBaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use messages\services\SystemService;
use order\services\OrderService;
use yii\helpers\ArrayHelper;
/**
 * MessageController implements the CRUD actions for MessageModel model.
 */
class MessageController extends WebBaseController
{
    public $layout = "main";
    const EBusinessID='1256641'; //电商ID
    const AppKey='e0d5fc9c-176c-441c-affe-d43f15b53242';  //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    const ReqURL='http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx';  //请求url

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }

    /**
     * 所有消息列表.
     * @return mixed
     */
    public function actionAll_list()
    {
        $data['customer_id'] = $this->getUserId();

        $system = SystemMsg::oneMsg(['type' => 1]);
        $favour = SystemMsg::oneMsg(['type' => 2]);
        $logistics = LogisticsMsg::oneMsg($data);
        return $this->render('all_list',[
            'system' => $system,
            'favour' => $favour,
            'logistics' => $logistics
        ]);
    }

    /**
     * 系统消息列表.
     * @return mixed
     */
    public function actionSystem_list()
    {
        $data = yii::$app->request->get();
        $data['type'] = 1;
        $result = SystemService::search($data);
        $list = $result['result']['list'];

        $result = self::groupByDate($list);
        return $this->render('system_list', [
            'result' => $result
        ]);
    }

    /**
     * 优惠消息列表.
     * @return mixed
     */
    public function actionFavour_list()
    {
        $data = yii::$app->request->get();
        $data['type'] = 2;
        $result = SystemService::search($data);
        $list = ArrayHelper::toArray($result['result']['list']);

        return $this->render('favour_list', [
            'list' => $list
        ]);
    }



    /**
     * 物流列表.
     * @return mixed
     */
    public function actionLogistics_list()
    {
        $data = [];
        $data['customer_id'] = $this->getUserId();
        $data['getByWeb'] = 1;
        $data['status'] = 0;
        $waitPay = OrderService::findOrder($data);
        $waitPay = ArrayHelper::toArray($waitPay['result']);
        $data['status'] = 4;
        $waitGet = OrderService::findOrder($data);
        $waitGet = ArrayHelper::toArray($waitGet['result']);
        $waitGetTitle = "-";
        if (sizeof($waitGet) > 0) {
            $waitGetItem = OrderService::findItems(['order_id'=>$waitGet[0]['order_id'],'getByWeb'=>1]);
            $waitGetItem = ArrayHelper::toArray($waitGetItem);
            $waitGetTitle = $waitGetItem[0]['product_title'];
        }
        $data['status'] = 5;
        $waitComment = OrderService::findOrder($data);
        $waitComment = ArrayHelper::toArray($waitComment['result']);
        return $this->render('logistics_list', [
            'waitPay' => $waitPay,
            'waitGet' => $waitGet,
            'waitGetTitle' => $waitGetTitle,
            'waitComment' => $waitComment,
        ]);
    }

    /**
     * 更新物流订单物流信息
     */
    function actionupdateOrderlogist(){

    }

    /**
     * 快的接口
     */
    function actionLogist(){
       $res['order_id'] = yii::$app->request->get('order_id');
       $res['getByWeb']=1;
       if(empty($res['order_id'])){
           return '订单不存在';
       }

      $logisticInfo = OrderService::findOrder($res);
      $logisticInfo = ArrayHelper::toArray($logisticInfo['result'][0]);
      $zto = $logisticInfo['express_code']; //快递编码
      $sn = $logisticInfo['express_sn'];   //快递单号

        //调用获取物流轨迹
        /**
         * 快递名称
         * 物流号
         */
        //-------------------------------------------------------------
        //$logisticResult = $this->getOrderTracesByJson('STO', '227426525563');
         $logisticResult = $this->getOrderTracesByJson($zto, $sn);
         return $this->render('logistics', ['logisticResult'=>$logisticResult]);

        //-------------------------------------------------------------

    }
    /**
     * Json方式 查询订单物流轨迹
     */
    function getOrderTracesByJson($shipperCode, $logisticCode){
        $requestData= "{\"OrderCode\":\"\",\"ShipperCode\":\"".$shipperCode."\",\"LogisticCode\":\"".$logisticCode."\"}";
        $datas = array(
            'EBusinessID' => self::EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData),
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, self::AppKey);
        $result=$this->sendPost(self::ReqURL, $datas);
        $result = (array)json_decode($result);
        $result['type']='';
        if(isset($result['State'])){
            if($result['State']==2){
                $result['type']='在途中';
            }elseif($result['State']==3){
                $result['type']='已签收';
            }else{
                $result['type']='问题件';
            }
        }else{
            $result['type']='未知物流';
        }

        //根据公司业务处理返回的信息......
        return $result;
    }

    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], 80);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }


    /**
     * 根据日期分组
     * @return mixed
     */
    private static function groupByDate($list) {
        $today = 0;//当前日期
        $day_key = 0;//被比对日期
        $all_msg = [];//总体
        //组
        $today_msg = [];//相同天数为一组
        foreach ($list as $k => $v) {
            $arr = ArrayHelper::toArray($v);
            if ($k == 0) {
                $day_key = date('Y.m.d', $arr['updated_at']);
                array_push($today_msg, $arr);
                continue;
            }else if ($k == count($list) - 1) {
                array_push($all_msg, $today_msg);
            }else {
                $today = date('Y.m.d', $arr['updated_at']);
                if ($today == $day_key) {
                    array_push($today_msg, $arr);
                    continue;
                }else{
                    array_push($all_msg, $today_msg);
                    $today_msg = [];
                    $day_key = date('Y.m.d', $arr['updated_at']);
                    array_push($today_msg, $arr);
                    continue;
                }
            }
        }
        return $all_msg;
    }
}
